#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API Key到用户信息的中间件
"""

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from src.utils.token_generator import token_generator
from src.utils.logger import get_logger
import config

logger = get_logger("capcut")


class ApiKeyToUserMiddleware(BaseHTTPMiddleware):
    """API Key到用户信息的中间件 - 只负责解析用户信息"""
    
    def __init__(self, app):
        super().__init__(app)
        self.header_name = config.JWT_HEADER_NAME
    
    def extract_api_key(self, request: Request) -> str:
        """从请求头中提取API Key"""
        # 从自定义头部提取
        api_key = request.headers.get(self.header_name)
        if api_key:
            # 如果用户已经包含Bearer前缀，去掉它
            if api_key.startswith("Bearer "):
                api_key = api_key[7:]
            return api_key
        
        # 从标准Authorization头部提取（兼容性）
        auth_header = request.headers.get("Authorization")
        if auth_header and auth_header.startswith("Bearer "):
            return auth_header[7:]
        
        return None
    
    async def dispatch(self, request: Request, call_next):
        """中间件主要逻辑 - 只解析用户信息，不做认证拦截"""
        # 提取API Key
        api_key = self.extract_api_key(request)
        
        if api_key:
            # 尝试解析用户信息
            try:
                payload = token_generator.verify_token(api_key)
                if payload:
                    # 提取用户信息
                    user_id = payload.get("user_id")
                    username = payload.get("username")
                    
                    if user_id:
                        # 将用户信息添加到请求状态中
                        request.state.user_id = user_id
                        request.state.username = username
                        request.state.api_key = api_key
                        request.state.token_payload = payload
                        
                        logger.info(f"解析用户信息成功: {username} (ID: {user_id})")
                        logger.info(f"解析用户信息成功: {request.state})")
                    else:
                        logger.debug("API Key中缺少用户ID")
                else:
                    logger.debug("API Key验证失败")
            except Exception as e:
                logger.debug(f"解析API Key异常: {str(e)}")
        
        # 继续处理请求（无论是否有有效的API Key）
        response = await call_next(request)
        return response


def get_user_from_request(request: Request) -> dict:
    """从请求中获取用户信息的辅助函数"""
    if hasattr(request.state, 'user_id'):
        return {
            'user_id': request.state.user_id,
            'username': request.state.username,
            'api_key': request.state.api_key,
            'payload': request.state.token_payload
        }
    return None 